package com.threeti.mecool.mobile.controller;

import com.threeti.mecool.mobile.Commander;
import com.threeti.mecool.mobile.interfaces.ResponserDto;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/upload")
public class FileUploadController {
    Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    @Value("${file.repo.upload.path}")
    private String uploadPath;

    /**
     * Upload files
     * @return file name in repository
     */
    @RequestMapping(value = "/uploadstep", method = RequestMethod.POST)
    @ResponseBody
    public ResponserDto uploadFile(@RequestParam("login_name") String userLoginName,
                                   @RequestParam("plan_id") Long planId,
                                   @RequestParam("plan_project_code_list") String planProjectCodeStr,
                                   @RequestParam("plan_job_id_list") String planJobIdStr,
                                   @RequestParam("step_id_list") String stepIdStr,
                                   @RequestParam("files") MultipartFile[] files) {
        try {
            String[] planProjectCodeArray = StringUtils.split(planProjectCodeStr, ',');
            String[] planJobIdArray = StringUtils.split(planJobIdStr, ',');
            String[] stepIdArray = StringUtils.split(stepIdStr, ',');
            if (planProjectCodeArray.length == planJobIdArray.length &&
                    planJobIdArray.length == stepIdArray.length &&
                    stepIdArray.length == files.length) {
                ResponserDto ret = ResponserDto.successCommand(Commander.command());
                try {
                    String time = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + "_" + files.length;
                    List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>(files.length);
                    for (int i = 0; i < files.length; i++) {
                        MultipartFile file = files[i];
                        String name = file.getOriginalFilename();
                        if (name.indexOf('.') != -1) {
                            name = String.format("/%s/%s-%d%s", userLoginName, time, i + 1, name.substring(name.lastIndexOf('.')));
                        } else {
                            name = String.format("/%s/%s-%d", userLoginName, time, i + 1);
                        }
                        OutputStream out = new BufferedOutputStream(FileUtils.openOutputStream(new File(uploadPath + name)));
                        out.write(file.getBytes());
                        out.close();

                        Map<String, Object> retObject = new HashMap<String, Object>();
                        retObject.put("plan_id", planId);
                        retObject.put("plan_project_code", planProjectCodeArray[i]);
                        retObject.put("plan_job_id", Integer.parseInt(planJobIdArray[i]));
                        retObject.put("step_id", Integer.parseInt(stepIdArray[i]));
                        //<-
                        retObject.put("name", name);
                        retList.add(retObject);
                    }
                    ret.withBizSuccessBody("files", retList);
                } catch (Exception e) {
                    ret = ResponserDto.withBizFailureMsg(Commander.command(), "err_upload", e.toString());
                }
                return ret;
            } else {
                return ResponserDto.withBizFailureMsg(Commander.command(), "UP_FILE", "参数长度不符");
            }
        } catch (Exception e) {
            logger.error("upload file", e);
            return ResponserDto.withBizFailureMsg(Commander.command(), "err_upload", e.getMessage());
        }
    }
}
